<template>
  <div class="customer-address-table-container">
    <el-table
      v-loading="listLoading"
      stripe
      :data="addressList"
      border
      :highlight-current-row="false"
      header-row-class-name="common-list-table-header__v2">
      <template slot="empty">
        <BaseListForNoData
          v-show="!listLoading"
          table-type="smallTable"
          :notice-msg="$t('common.base.tip.noData')"
        ></BaseListForNoData>
      </template>

      <el-table-column
        v-for="(column, index) in columns"
        v-if="column.show"
        :key="`${column.field}_${index}`"
        :label="column.label"
        :prop="column.field"
        :width="column.width"
        :min-width="column.minWidth"
        :sortable="column.sortable"
        :show-overflow-tooltip="column.tooltip"
        :align="column.align">
        <template slot-scope="scope">
          <template v-if="column.field === 'area'">
            <a v-if="allowEditCustomer" href="javascript:;" @click="openDialog(scope.row)" class="edit-btn">{{scope.row[column.field] || $t('customer.detail.customerAddressTable.areaCol.repair')}}</a>
            <template v-else>{{scope.row[column.field]}}</template>
          </template>
          <div v-else-if="column.field === 'action'" class="action">
            <el-dropdown class="dropdown">
              <span class="cur-point">
                {{$t('common.base.more')}}<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown" class="lang-select-dropdown">
                <el-dropdown-item v-if="scope.row.isMain" disabled>
                  <div>{{$t('customer.detail.customerAddressTable.areaCol.defaultAddress')}}</div> 
                </el-dropdown-item>
                <el-dropdown-item v-if="!scope.row.isMain" :disabled="pending[scope.row.id]">
                  <div @click="setDefaultAddress(scope.row)">
                    {{$t('customer.detail.customerAddressTable.areaCol.setDefault')}}
                  </div> 
                </el-dropdown-item>
                <el-dropdown-item :disabled="pending[scope.row.id]">
                  <div @click="deleteAddress(scope.row)">{{$t('common.base.delete')}}</div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div class="form-view-row-content-address" v-else-if="column.field === 'address'" :class="{'can-open-map': scope.row.longitude && scope.row.latitude, }" @click.stop="openMap(scope.row)">
            <i class="iconfont icon-address customer-address-icon" @click.stop="openMap(scope.row)"
               v-if="scope.row.longitude && scope.row.latitude"></i>
            {{scope.row[column.field]}}
          </div>
          <template v-else>
            {{scope.row[column.field]}}
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <BaseAddOnPagination :paginationInfo="paginationInfo" @pageJump="jump" @sizeChange="handleSizeChange" />

    <edit-address-dialog ref="addAddressDialog" :customer-id="customerId"
                         :login-user-id="shareData.loginUser.userId" action="edit" @submit-success="fetchData"
                         :default-address="selectedAddress"></edit-address-dialog>
  </div>
</template>

<script>
import { formatDate } from 'pub-bbx-utils';
import platform from '@src/platform'
import EditAddressDialog from '../operationDialog/EditAddressDialog.vue';
import _ from 'lodash';
import { safeNewDate } from '@src/util/time';
import { getRootWindow } from '@src/util/dom'
import { fmtDist } from '@src/util/addressUtil';

export default {
  name: 'customer-address-table',
  props: {
    shareData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      addressList: [],
      selectedAddress: {},
      pending: {},
      columns: [],
      paginationInfo: {
        pageSize: 10,
        pageNum: 1,
        totalItems: 0,
      },
      listLoading: true
    }
  },
  computed: {
    customerId() {
      return this.shareData.customer ? this.shareData.customer.id : '';
    },
    allowEditCustomer() {
      return !this.shareData.isDelete && !this.shareData.isDisable && this.shareData.allowEditCustomer;
    },
    isAddressAllowNull() {
      return this.shareData.isAddressAllowNull;
    },
    // 是否开启客户地址编号灰度
    isCustomerAddressNum() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.customerAddressNum || false
    },
  },
  mounted() {
    this.fetchData();
    this.columns = this.buildColumns();
    this.$eventBus.$on('customer_address_table.update_address_list', this.fetchData);
  },
  beforeDestroy() {
    this.$eventBus.$off('customer_address_table.update_address_list', this.fetchData);
  },
  methods: {
    openDialog(address) {
      if (!this.allowEditCustomer) return;
      this.selectedAddress = address;
      this.$nextTick(() => {
        this.$refs.addAddressDialog.openDialog();
      });

    },
    async deleteAddress(address) {
      if (address.isMain && !this.isAddressAllowNull) return platform.alert(this.$t('customer.detail.customerAddressTable.delAddress.canNot'));
      try {
        if (!await platform.confirm(this.$t('customer.detail.customerAddressTable.delAddress.confirmMsg'))) return;
        this.pending[address.id] = true;
        const reqRes = await this.$http.post('/customer/address/delete', {ids: address.id, }, false);
        delete this.pending[address.id];
        if (reqRes.status === 0) {
          this.fetchData();
        } else {
          platform.alert(reqRes.message);
        }
        this.$eventBus.$emit('customer_info_record.update_record_list');
        this.$eventBus.$emit('customer_detail_view.update_statistical_data');
        if (address.isMain) {
          this.$eventBus.$emit('customer_detail_view.update_customer_detail');
        }
      } catch (e) {
        console.error('err',);
      }
    },
    setDefaultAddress(address) {
      if (this.pending[address.id]) return;
      this.pending[address.id] = true;
      this.$http.post('/customer/address/setMain', {id: address.id}, false)
        .then(res => {
          if (res.status === 0) {
            this.fetchData();
          } else {
            platform.alert(res.message);
          }
          this.pending[address.id] = false;
          this.$eventBus.$emit('customer_detail_view.update_customer_detail');
        })
        .catch(e => console.error('caught e', e));
    },
    openMap(address) {
      if (!address.longitude && !address.latitude) return;

      const ad = {
        ...address,
        adLongitude: address.longitude,
        adLatitude: address.latitude,
      };

      this.$fast.map.display(ad, {title: this.$t('customer.detail.customerAddressTable.openMap.title'), })
        .catch(err => console.error('openMap catch an err: ', err));
    },

    jump(pN) {
      this.paginationInfo.pageNum = pN;
      this.fetchData();
    },
    handleSizeChange(pageSize) {
      this.paginationInfo.pageSize = pageSize;
      this.paginationInfo.pageNum = 1;
      this.fetchData();
    },
    fetchData() {
      this.listLoading = true;
      const params = {
        customerId: this.customerId,
        pageNum: this.paginationInfo.pageNum,
        pageSize: this.paginationInfo.pageSize,
      };
        
      this.$http.get('/customer/address/list', params)
        .then(res => {
          this.addressList = res.list
            .map(address => {
              this.$set(this.pending, address.id, !!address.isMain && !this.isAddressAllowNull);
              const { showAddress } = address;
              address.area = fmtDist(showAddress ? showAddress : address);
              address.createTime = formatDate(safeNewDate(address.createTime), 'YYYY-MM-DD HH:mm:ss');
              return Object.freeze(address);
            });

          this.paginationInfo.totalItems = res.total;
        })
        .catch(e => console.error('caught e', e))
        .finally(() => {
          this.listLoading = false
        })
    },
    buildColumns() {
      // 开利客户地址编号
      let extendFiled= [
        {
          label: this.$t('common.label.serialNumber'),
          field: 'addressNum',
          show: true,
          minWidth: '200px',
          tooltip: true,
        }, 
      ]
      let fields = [
      {
        label: this.$t('customer.detail.customerAddressTable.table.label.area'),
        field: 'area',
        show: true,
        minWidth: '200px',
        tooltip: true,
        // sortable: 'custom',
      }, {
        label: this.$t('customer.detail.customerAddressTable.table.label.address'),
        field: 'address',
        show: true,
        minWidth: '200px',
        tooltip: true
      }, {
        label: this.$t('customer.detail.customerAddressTable.table.label.action'),
        field: 'action',
        show: this.allowEditCustomer,
        tooltip: false,
        width: '120px',
      }]

      if (this.isCustomerAddressNum) {
        fields.splice(0, 0, ...extendFiled)
      }
      return fields
    }
  },
  components: {
    EditAddressDialog,
    [EditAddressDialog.name]: EditAddressDialog,
  }
}
</script>

<style lang="scss" scoped>

  .customer-address-table-container {
    padding: 16px;

    .can-open-map:hover {
      cursor: pointer;
    }

    .edit-btn {
      @include fontColor();
    }

    .action {
      display: flex;
      justify-content: space-between;
      .default {
        color: #666!important;
        font-size: 13px!important;
        padding: 14px 0px!important;
        cursor: text;
      }
    }

    .set-default {
      padding: 13px 0px!important;
    }

    .delete-address-btn {
      color: $color-danger;
      min-width: auto!important;
    }

    .customer-address-table-container .delete-address-btn.is-disabled,
    .customer-address-table-container .delete-address-btn.is-disabled:hover, 
    .customer-address-table-container .el-button.delete-address-btn:focus{
      color: #c0c4cc;
      cursor: not-allowed;
      background-image: none;
    }

    .address-table-footer {
      display: flex;
      justify-content: space-between;

      .total-count {
        padding: 0 10px;
        font-size: 12px;
        margin: 0;
        line-height: 46px;
        span {
          padding: 0 5px;
          @include fontColor();
        }
      }
    }
  }
  .form-view-row-content-address:hover{
    color: $color-primary-light-6;
  }
.cur-point {
  color: $color-primary-light-6;
}
.lang-select-dropdown {
  margin-top: 0!important;
}
</style>